package com.ccys.doctor.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.ccys.common.util.HtmlUtils;
import com.ccys.db.cache.TranslationUtil;
import com.ccys.db.dto.consultation.MedicationCertificationPdfVo;
import com.ccys.db.mapper.TblBookingConsultNoteMapper;
import com.ccys.db.mapper.TblBookingMapper;
import com.ccys.db.vo.consultation.MemoPDFVo;
import com.ccys.db.vo.consultation.ReferralLetterPDFVo;
import com.ccys.doctor.service.PDFDocumentService;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;

import static com.ccys.db.cache.TranslationUtil.getContentLastLanguage;

/**
 * @Author：XLY
 * @Date：2024/2/7 0007
 */
@Service
@Slf4j
public class PDFDocumentServiceImpl implements PDFDocumentService {

    @Resource
    private TblBookingConsultNoteMapper consultNoteMapper;

    @Resource
    private TblBookingMapper tblBookingMapper;


    private MemoPDFVo getMemoData(String bookingId) {
        //memo_note 只有印尼才展示 country_of_residence = 106 -> 从翻译表里面找值 MEMO_NOTE
        //visible -> tbl_company 里面 powered_by_memo
        //visiblePatientClinic -> 和RF一样
        MemoPDFVo data = consultNoteMapper.getMemoPdfData(bookingId);
        //国际化
        data.setNameText(getContentLastLanguage("NAME", data.getLastLanguage()));
        data.setIdNoText(getContentLastLanguage("ID_NO", data.getLastLanguage()));
        data.setMCRNoText(getContentLastLanguage("MCR_NO", data.getLastLanguage()));
        data.setPartnershipWithText(getContentLastLanguage("IN_PARTNERSHIP_WITH", data.getLastLanguage()));
        data.setVisitDateText(getContentLastLanguage("VISITDATE", data.getLastLanguage()));
        //印尼才展示memoNote
        if ("106".equals(data.getPatientCountry())) {
            data.setMemoNote(getContentLastLanguage("MEMO_NOTE", data.getLastLanguage()));
        }

        return data;
    }

    @Override
    public byte[] generateMemoPdf(String bookingId) {
        try {
            MemoPDFVo data = getMemoData(bookingId);
            HashMap<String, Object> mapData = Maps.newHashMap();
            mapData.put("data", data);
            String templateContent = HtmlUtils.getTemplateContent("MemoPDF.ftl", mapData);
            byte[] bytes = HtmlUtils.html2Pdf(templateContent);
            return bytes;
        } catch (Exception e) {
            log.error(e.getMessage());

        }
        return null;
    }

    @Override
    public String generateCustomMemoPdf(String bookingId, String memo) {
        MemoPDFVo data = getMemoData(bookingId);
        if (StringUtils.isNotEmpty(memo)) {
            data.setName(memo);
        }
        HashMap<String, Object> mapData = Maps.newHashMap();
        mapData.put("data", data);
        String templateContent = null;
        try {
            templateContent = HtmlUtils.getTemplateContent("MemoPDF.ftl", mapData);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return templateContent;
    }

    @Override
    public byte[] generateMedicalCertificatePdf(String bookingId) {
        //查询数据
        MedicationCertificationPdfVo data = tblBookingMapper.getMedicationCertificationPdfData(bookingId);
        //判断不为空才进入
        if (ObjectUtil.isNotEmpty(data)) {
            // dd表示日，MMM表示月份的缩写形式，yy表示两位数的年份
            // 使用Locale.ENGLISH来确保月份的缩写是英文的
            SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yy", Locale.ENGLISH);
            //判断是否有病假条:0-否,1-是
            if (1 == data.getNeedMedicalCertification()) {
                //判断全都不为空才行
                if (ObjectUtil.isNotEmpty(data.getMedicalCertificationDays())
                        && ObjectUtil.isNotEmpty(data.getMedicalCertificationBeginDate())) {
                    //开始转换时间格式
                    // 使用format()方法将日期转换
                    String strDate = formatter.format(data.getMedicalCertificationBeginDate());
                    //开始拼接病假条
                    data.setSickLetterNote("The above mentioned individual has been certified Unfit <br>" +
                            "for Duty for " + data.getMedicalCertificationDays() + " day " + "with effect from " + strDate);
                }

            }
            //设置当前时间并且转换
            data.setCurrentDate(formatter.format(new Date()));
            //设置VisitDate
            data.setVisitDate(formatter.format(data.getCreatedOn()));
            //国际化
            String lastLanguage = data.getLastLanguage();
            data.setMcrNoText(TranslationUtil.getContentLastLanguage("MCR_NO", lastLanguage));
            data.setIdNoText(TranslationUtil.getContentLastLanguage("ID_NO", lastLanguage));
            data.setNameText(TranslationUtil.getContentLastLanguage("NAME", lastLanguage));
            data.setVisitDateText(TranslationUtil.getContentLastLanguage("VISITDATE", lastLanguage));
            data.setCertificateNoText(TranslationUtil.getContentLastLanguage("CERTIFICATE_NO", lastLanguage));
            data.setNoteText(TranslationUtil.getContentLastLanguage("NOTE", lastLanguage));
            HashMap<String, Object> mapData = Maps.newHashMap();
            mapData.put("data", data);
            String templateContent = null;
            try {
                templateContent = HtmlUtils.getTemplateContent("MedicalCertificate.ftl", mapData);
            } catch (Exception e) {
                log.error(e.getMessage());
            }
            return HtmlUtils.html2Pdf(templateContent);
        }


        return null;
    }

    @Override
    public byte[] generateReferralLetterPdf(String bookingId) {
        String templateContent = generateReferralLetterHtml(bookingId);
        return HtmlUtils.html2Pdf(templateContent);

    }

    @Override
    public String generateReferralLetterHtml(String bookingId) {
        // visible -> tbl_company里面powered_by_referral_letter
        // visible_Patient_Clinic -> 如果tbl_clinic的的id 与 tbl_booking_patient_address 的clinic_id 不相等，那就为"block"
        // Visible_MCR_No -> if tbl_Doctor.doctor_license_no is not null -> 1 = show, 0 = hide
        // Visible_Pharmacy_Address  is_show_pharmacy_address(return from the SP) is 1
        // Kind regards 使用翻译表对应

        ReferralLetterPDFVo data = consultNoteMapper.getReferralLetterPdfData(bookingId);
        //国际化
        data.setReferralLetterText(getContentLastLanguage("REFERRAL_LETTER", data.getLastLanguage()));
        data.setKindRegardsText(getContentLastLanguage("KIND_REGARDS", data.getLastLanguage()));
        data.setNameText(getContentLastLanguage("NAME", data.getLastLanguage()));
        data.setIdNoText(getContentLastLanguage("ID_NO", data.getLastLanguage()));
        data.setMCRNoText(getContentLastLanguage("MCR_NO", data.getLastLanguage()));
        data.setPartnershipWithText(getContentLastLanguage("IN_PARTNERSHIP_WITH", data.getLastLanguage()));
        data.setVisitDateText(getContentLastLanguage("VISITDATE", data.getLastLanguage()));
        data.setRefDoctorNameComma(getContentLastLanguage(data.getRefDoctorName(), data.getLastLanguage()));
        if (org.apache.commons.lang.StringUtils.isBlank(data.getRefDoctorNameComma())) {
            data.setRefDoctorNameComma(data.getRefDoctorName());
        }
        HashMap<String, Object> mapData = Maps.newHashMap();
        mapData.put("data", data);
        String templateContent = null;
        try {
            templateContent = HtmlUtils.getTemplateContent("ReferralLetterPDF.ftl", mapData);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return templateContent;
    }
}
